package com.lkf.simplewebcontainer.servlet;

import com.lkf.simplewebcontainer.http.Request;
import com.lkf.simplewebcontainer.http.Response;
import io.netty.handler.codec.http.HttpResponseStatus;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;

/**
 * 文件类型静态资源Servlet实现
 */
public class FileServlet extends Servlet {
    // 静态资源地址
    private String staticPath;
    // 静态资源
    private File file;

    public FileServlet(String staticPath, File file) {
        this.staticPath = staticPath;
        this.file = file;
    }

    @Override
    public void doGet(Request request, Response response) throws Exception {
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        String contentType = mimeTypesMap.getContentType(file);
        // 文本文件中的内容使用utf8编码
        if (contentType.equals("text/plain")) {
            contentType = "text/plain;charset=utf-8";
        }
        response.writeFile(file, HttpResponseStatus.OK, contentType);
    }

    @Override
    public void doPost(Request request, Response response) throws Exception {
        doGet(request, response);
    }
}
